//! # 重构后工具集成测试
//!
//! 此测试文件验证重构后的工具类是否能正常工作，
//! 包括 Principal 构建器、权限检查器、HTTP 客户端工具和配置构建器。

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::time::Duration;

    #[cfg(feature = "auth-tools")]
    use rustcloud_core::auth::{PrincipalBuilder, PrincipalConverter, PermissionCheckerFactory};
    #[cfg(feature = "http-tools")]
    use rustcloud_core::http_client::{HttpClientConfig, HttpClientFactory};
    #[cfg(feature = "config-tools")]
    use rustcloud_core::config_builder::{ConnectionPoolConfig, RetryConfig, ConfigFactory};

    /// 测试 Principal 构建器功能
    #[cfg(feature = "auth-tools")]
    #[tokio::test]
    async fn test_principal_builder_refactored() {
        // 测试从 JWT Claims 创建 Principal
        let mut claims = HashMap::new();
        claims.insert("name".to_string(), serde_json::Value::String("测试用户".to_string()));
        claims.insert("user_type".to_string(), serde_json::Value::String("admin".to_string()));
        claims.insert("roles".to_string(), serde_json::Value::Array(vec![
            serde_json::Value::String("admin".to_string()),
        ]));

        let principal = PrincipalConverter::from_jwt_claims("user123".to_string(), &claims).build();
        
        assert_eq!(principal.id, "user123");
        assert_eq!(principal.name, "测试用户");
        assert!(principal.get_roles().contains(&"admin".to_string()));
    }

    /// 测试权限检查器功能
    #[cfg(feature = "auth-tools")]
    #[tokio::test]
    async fn test_permission_checker_refactored() {
        let checker = PermissionCheckerFactory::create_default();
        
        // 创建一个具有管理员角色的 Principal
        let admin_principal = PrincipalBuilder::new("admin001".to_string())
            .name("管理员".to_string())
            .role("admin".to_string())
            .build();

        // 管理员应该有所有权限
        let has_permission = checker.check(&admin_principal, "users:write").await.unwrap();
        assert!(has_permission);
    }

    /// 测试 HTTP 客户端工具功能
    #[cfg(feature = "http-tools")]
    #[test]
    fn test_http_client_config_refactored() {
        // 测试预定义配置
        let config_client_config = HttpClientConfig::for_config_client();
        assert_eq!(config_client_config.timeout, Duration::from_secs(10));
        assert_eq!(config_client_config.user_agent, "RustCloud-Config-Client/1.0");

        let transport_config = HttpClientConfig::for_transport();
        assert_eq!(transport_config.timeout, Duration::from_secs(5));
        assert_eq!(transport_config.user_agent, "RustCloud-Transport/1.0");

        let gateway_config = HttpClientConfig::for_gateway();
        assert_eq!(gateway_config.timeout, Duration::from_secs(30));
        assert_eq!(gateway_config.max_connections, 200);

        // 测试自定义构建器
        let custom_config = HttpClientConfig::builder()
            .timeout(Duration::from_secs(15))
            .retry_count(5)
            .max_connections(150)
            .user_agent("Custom-Client/1.0".to_string())
            .build()
            .unwrap();

        assert_eq!(custom_config.timeout, Duration::from_secs(15));
        assert_eq!(custom_config.retry_count, 5);
        assert_eq!(custom_config.max_connections, 150);
        assert_eq!(custom_config.user_agent, "Custom-Client/1.0");
    }

    /// 测试配置构建器功能
    #[cfg(feature = "config-tools")]
    #[test]
    fn test_config_builders_refactored() {
        // 测试工厂方法
        let dev_pool = ConfigFactory::create_dev_connection_pool();
        assert_eq!(dev_pool.max_connections, 20);

        let prod_pool = ConfigFactory::create_prod_connection_pool();
        assert_eq!(prod_pool.max_connections, 100);

        let fast_retry = ConfigFactory::create_fast_retry();
        assert_eq!(fast_retry.max_attempts, 3);

        // 测试构建器
        let custom_pool = ConnectionPoolConfig::builder()
            .max_connections(50)
            .min_connections(5)
            .connection_timeout(Duration::from_secs(10))
            .build()
            .unwrap();

        assert_eq!(custom_pool.max_connections, 50);
        assert_eq!(custom_pool.min_connections, 5);
        assert_eq!(custom_pool.connection_timeout, Duration::from_secs(10));

        let custom_retry = RetryConfig::builder()
            .max_attempts(7)
            .base_delay(Duration::from_millis(200))
            .exponential_backoff(true)
            .build()
            .unwrap();

        assert_eq!(custom_retry.max_attempts, 7);
        assert_eq!(custom_retry.base_delay, Duration::from_millis(200));
        assert!(custom_retry.exponential_backoff);
    }

    /// 综合测试：模拟实际使用场景
    #[cfg(all(feature = "auth-tools", feature = "http-tools", feature = "config-tools"))]
    #[tokio::test]
    async fn test_integrated_refactored_tools() {
        // 1. 创建用户主体
        let principal = PrincipalBuilder::new("user123".to_string())
            .name("测试用户".to_string())
            .role("user".to_string())
            .permission("orders:read".to_string())
            .build();

        // 2. 验证权限
        let permission_checker = PermissionCheckerFactory::create_default();
        let has_permission = permission_checker.check(&principal, "orders:read").await.unwrap();
        assert!(has_permission);

        // 3. 创建 HTTP 配置
        let http_config = HttpClientConfig::for_gateway();
        assert!(http_config.validate().is_ok());

        // 4. 创建连接池配置
        let pool_config = ConfigFactory::create_prod_connection_pool();
        assert!(pool_config.validate().is_ok());

        println!("✅ 所有重构后的工具都正常工作！");
    }

    /// 性能基准测试
    #[cfg(feature = "auth-tools")]
    #[tokio::test]
    async fn test_performance_refactored() {
        let start = std::time::Instant::now();
        
        // 创建多个 Principal
        for i in 0..1000 {
            let principal = PrincipalBuilder::new(format!("user{}", i))
                .name(format!("用户{}", i))
                .role("user".to_string())
                .build();
            assert_eq!(principal.id, format!("user{}", i));
        }
        
        let duration = start.elapsed();
        println!("创建 1000 个 Principal 耗时: {:?}", duration);
        
        // 性能应该在合理范围内（少于100ms）
        assert!(duration < Duration::from_millis(100));
    }
}